<?php

namespace app\helper;

use Sunqianhu\Helper\Time;
use think\facade\Cache;

class LoginCountCheckerHelper
{
    /**
     * @var string
     */
    public string $cacheKey = '';
    /**
     * @var int 次数
     */
    public int $number = 5;
    /**
     * @var int 时间
     */
    public int $time = 60 * 60;

    /**
     * 构造
     * @param $account
     */
    public function __construct($account)
    {
        $this->cacheKey = 'login_fail_checker_'.md5($account);
    }

    /**
     * 设置失败
     * @return void
     */
    public function setFail()
    {
        $number = Cache::get($this->cacheKey) ?? 0;
        $number ++;
        Cache::set($this->cacheKey, $number, $this->time);
    }

    /**
     * 重设失败
     * @return void
     */
    public function resetFail(){
        Cache::delete($this->cacheKey);
    }

    /**
     * 检查
     * @return bool
     */
    public function check()
    {
        $number = Cache::get($this->cacheKey) ?? 0;
        if($number < $this->number){
            return true;
        }
        return false;
    }

    /**
     * 得到可用次数
     * @return int
     */
    public function getAvailableNumber()
    {
        $number = Cache::get($this->cacheKey) ?? 0;
        return $this->number - $number;
    }

    /**
     * 得到重置可读时间
     * @return string
     */
    public function getResetReadableTime(){
        $time = new Time();
        return $time->getSecondToReadableTime($this->time);
    }
}